﻿// B.MESUI.Login/A_Public/Service/CodeGenService.cs
using System.Collections.Generic;
using System.Threading.Tasks;
using B.MESUI.Login.A_Public.Model;
using B.MESUI.Login.A_Public.Helpers;
using Newtonsoft.Json;

namespace B.MESUI.Login.A_Public.Service
{
    public static class CodeGenService
    {
        public static async Task<string> GenerateCodeAsync(string ruleName)
        {
            var url = HttpClientHelper.GetCodeGenUrl("api/Code/generate");
            var req = new { ruleName };
            var resp = await HttpClientHelper.PostAsync(url, req);
            dynamic obj = JsonConvert.DeserializeObject(resp);
            return obj.code;
        }

        public static async Task<bool> CreateRuleAsync(string ruleName, string prefix, string connector, int serialLength)
        {
            var url = HttpClientHelper.GetCodeGenUrl("api/Code/rule");
            var req = new { ruleName, prefix, connector, serialLength };
            var resp = await HttpClientHelper.PostAsync(url, req);
            dynamic obj = JsonConvert.DeserializeObject(resp);
            return obj.success == true;
        }

        public static async Task<List<RuleViewModel>> GetAllRulesAsync()
        {
            var url = HttpClientHelper.GetCodeGenUrl("api/Code/rules");
            var resp = await HttpClientHelper.GetAsync(url);
            dynamic obj = JsonConvert.DeserializeObject(resp);
            var rules = new List<RuleViewModel>();
            if (obj.rules != null)
            {
                foreach (var r in obj.rules)
                {
                    rules.Add(new RuleViewModel
                    {
                        ruleName = r.ruleName,
                        prefix = r.prefix,
                        connector = r.connector,
                        serialLength = r.serialLength
                    });
                }
            }
            return rules;
        }

        public static async Task<RuleViewModel> GetRuleDetailAsync(string ruleName)
        {
            var url = HttpClientHelper.GetCodeGenUrl("api/Code/rule/detail");
            var req = new { ruleName };
            var resp = await HttpClientHelper.PostAsync(url, req);
            dynamic obj = JsonConvert.DeserializeObject(resp);
            if (obj == null || obj.rule == null) return null;
            var rule = obj.rule;
            return new RuleViewModel
            {
                ruleName = rule.ruleName,
                prefix = rule.prefix,
                connector = rule.connector,
                serialLength = rule.serialLength
            };
        }

        public static async Task<string> PreviewCodeAsync(string ruleName)
        {
            var url = HttpClientHelper.GetCodeGenUrl("api/Code/preview");
            var req = new { ruleName };
            var resp = await HttpClientHelper.PostAsync(url, req);
            dynamic obj = JsonConvert.DeserializeObject(resp);
            return obj.code;
        }
    }
}